class ProfileManager {
    constructor() {
        this.apiBase = './api';
        this.currentUser = null;
        
        this.checkAuthentication()
            .then(() => {
                this.initializeEventListeners();
                this.loadUserProfile();
                this.handleUrlHash();
            })
            .catch(() => {
                // 未认证，跳转到登录页面
                window.location.href = 'auth.html';
            });
    }

    // 检查用户认证状态
    async checkAuthentication() {
        const token = localStorage.getItem('auth_token');
        const expires = localStorage.getItem('auth_expires');
        
        if (!token || !expires) {
            throw new Error('No auth token');
        }
        
        const expiresDate = new Date(expires);
        if (expiresDate <= new Date()) {
            this.clearAuthData();
            throw new Error('Token expired');
        }
        
        try {
            const response = await this.apiRequest('auth.php?action=verify', 'GET');
            if (response.success && response.data.valid) {
                this.currentUser = response.data.user;
                return true;
            } else {
                this.clearAuthData();
                throw new Error('Invalid token');
            }
        } catch (error) {
            this.clearAuthData();
            throw error;
        }
    }

    // 初始化事件监听器
    initializeEventListeners() {
        // 个人信息表单
        document.getElementById('profileInfoForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.updateProfile();
        });

        // 修改密码表单
        document.getElementById('changePasswordForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.changePassword();
        });

        // 密码强度检测
        document.getElementById('newPassword').addEventListener('input', (e) => {
            this.checkPasswordStrength(e.target.value);
        });

        // 确认密码验证
        document.getElementById('confirmNewPassword').addEventListener('input', () => {
            this.validatePasswordMatch();
        });

        // 实时输入验证
        this.setupInputValidation();
    }

    // 设置输入验证
    setupInputValidation() {
        const inputs = document.querySelectorAll('input:not([readonly])');
        inputs.forEach(input => {
            input.addEventListener('blur', () => this.validateInput(input));
            input.addEventListener('input', () => this.clearInputError(input));
        });
    }

    // 处理URL锚点
    handleUrlHash() {
        const hash = window.location.hash.substring(1);
        if (hash === 'password') {
            // 切换到修改密码标签页
            setTimeout(() => {
                showTab('password');
            }, 100);
        }
    }

    // 加载用户资料
    async loadUserProfile() {
        try {
            const response = await this.apiRequest('auth.php?action=profile', 'GET');
            
            if (response.success) {
                const user = response.data.user;
                
                // 填充表单数据
                document.getElementById('username').value = user.username || '';
                document.getElementById('email').value = user.email || '';
                document.getElementById('createdAt').value = this.formatDate(user.created_at) || '';
                document.getElementById('lastLogin').value = this.formatDate(user.last_login) || '从未登录';
                
                // 更新当前用户信息
                this.currentUser = user;
            } else {
                this.showNotification('加载用户信息失败', 'error');
            }
        } catch (error) {
            this.showNotification('网络错误，请稍后重试', 'error');
        }
    }

    // 更新个人资料
    async updateProfile() {
        const form = document.getElementById('profileInfoForm');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());

        if (!this.validateProfileForm(data)) {
            return;
        }

        this.showLoading();
        
        try {
            const response = await this.apiRequest('auth.php?action=profile', 'PUT', data);
            
            if (response.success) {
                this.showNotification('资料更新成功！', 'success');
                
                // 更新本地存储的用户信息
                const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
                userInfo.username = data.username;
                userInfo.email = data.email;
                localStorage.setItem('user_info', JSON.stringify(userInfo));
                
                // 重新加载用户资料
                setTimeout(() => {
                    this.loadUserProfile();
                }, 1000);
            } else {
                if (response.errors) {
                    this.displayFormErrors(response.errors);
                } else {
                    this.showNotification(response.message || '更新失败', 'error');
                }
            }
        } catch (error) {
            this.showNotification('网络错误，请稍后重试', 'error');
        } finally {
            this.hideLoading();
        }
    }

    // 修改密码
    async changePassword() {
        const form = document.getElementById('changePasswordForm');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());

        if (!this.validatePasswordForm(data)) {
            return;
        }

        this.showLoading();
        
        try {
            const response = await this.apiRequest('auth.php?action=password', 'PUT', data);
            
            if (response.success) {
                this.showNotification('密码修改成功！请重新登录', 'success');
                
                // 清空表单
                form.reset();
                this.hidePasswordStrength();
                
                // 3秒后跳转到登录页面
                setTimeout(() => {
                    this.clearAuthData();
                    window.location.href = 'auth.html';
                }, 3000);
            } else {
                if (response.errors) {
                    this.displayFormErrors(response.errors);
                } else {
                    this.showNotification(response.message || '密码修改失败', 'error');
                }
            }
        } catch (error) {
            this.showNotification('网络错误，请稍后重试', 'error');
        } finally {
            this.hideLoading();
        }
    }

    // 验证个人资料表单
    validateProfileForm(data) {
        let isValid = true;

        // 验证用户名
        if (!data.username || data.username.trim().length < 3) {
            this.showInputError('username', '用户名至少需要3个字符');
            isValid = false;
        } else if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(data.username)) {
            this.showInputError('username', '用户名只能包含字母、数字、下划线和中文');
            isValid = false;
        }

        // 验证邮箱
        if (!data.email || !this.isValidEmail(data.email)) {
            this.showInputError('email', '请输入有效的邮箱地址');
            isValid = false;
        }

        return isValid;
    }

    // 验证密码表单
    validatePasswordForm(data) {
        let isValid = true;

        // 验证当前密码
        if (!data.current_password) {
            this.showInputError('currentPassword', '请输入当前密码');
            isValid = false;
        }

        // 验证新密码
        if (!data.new_password || data.new_password.length < 6) {
            this.showInputError('newPassword', '新密码至少需要6个字符');
            isValid = false;
        }

        // 验证确认密码
        if (data.new_password !== data.confirm_password) {
            this.showInputError('confirmNewPassword', '两次输入的新密码不一致');
            isValid = false;
        }

        // 检查新密码不能与当前密码相同
        if (data.new_password === data.current_password) {
            this.showInputError('newPassword', '新密码不能与当前密码相同');
            isValid = false;
        }

        return isValid;
    }

    // 验证单个输入
    validateInput(input) {
        const value = input.value.trim();
        let isValid = true;
        let message = '';

        switch (input.id) {
            case 'username':
                if (value.length > 0 && value.length < 3) {
                    message = '用户名至少需要3个字符';
                    isValid = false;
                } else if (value.length > 0 && !/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(value)) {
                    message = '用户名只能包含字母、数字、下划线和中文';
                    isValid = false;
                }
                break;
            
            case 'email':
                if (value.length > 0 && !this.isValidEmail(value)) {
                    message = '请输入有效的邮箱地址';
                    isValid = false;
                }
                break;
            
            case 'newPassword':
                if (value.length > 0 && value.length < 6) {
                    message = '新密码至少需要6个字符';
                    isValid = false;
                }
                break;
            
            case 'confirmNewPassword':
                const newPassword = document.getElementById('newPassword').value;
                if (value.length > 0 && value !== newPassword) {
                    message = '两次输入的新密码不一致';
                    isValid = false;
                }
                break;
        }

        if (!isValid) {
            this.showInputError(input.id, message);
        } else {
            this.clearInputError(input);
        }

        return isValid;
    }

    // 验证密码匹配
    validatePasswordMatch() {
        const newPassword = document.getElementById('newPassword').value;
        const confirmPassword = document.getElementById('confirmNewPassword').value;
        
        if (confirmPassword.length > 0) {
            if (newPassword !== confirmPassword) {
                this.showInputError('confirmNewPassword', '两次输入的新密码不一致');
            } else {
                this.clearInputError(document.getElementById('confirmNewPassword'));
            }
        }
    }

    // 检查密码强度
    checkPasswordStrength(password) {
        const strengthElement = document.getElementById('newPasswordStrength');
        const strengthFill = strengthElement.querySelector('.strength-fill');
        const strengthText = strengthElement.querySelector('.strength-text');
        
        if (password.length === 0) {
            this.hidePasswordStrength();
            return;
        }
        
        strengthElement.classList.add('show');
        
        let strength = 0;
        let text = '弱';
        
        // 长度检查
        if (password.length >= 8) strength++;
        if (password.length >= 12) strength++;
        
        // 包含数字
        if (/\d/.test(password)) strength++;
        
        // 包含小写字母
        if (/[a-z]/.test(password)) strength++;
        
        // 包含大写字母
        if (/[A-Z]/.test(password)) strength++;
        
        // 包含特殊字符
        if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength++;
        
        // 设置强度样式和文本
        strengthFill.className = 'strength-fill';
        if (strength <= 2) {
            strengthFill.classList.add('weak');
            text = '弱';
        } else if (strength <= 3) {
            strengthFill.classList.add('fair');
            text = '一般';
        } else if (strength <= 4) {
            strengthFill.classList.add('good');
            text = '良好';
        } else {
            strengthFill.classList.add('strong');
            text = '强';
        }
        
        strengthText.textContent = `密码强度：${text}`;
    }

    // 隐藏密码强度指示器
    hidePasswordStrength() {
        const strengthElement = document.getElementById('newPasswordStrength');
        strengthElement.classList.remove('show');
    }

    // 显示输入错误
    showInputError(inputId, message) {
        const input = document.getElementById(inputId);
        const wrapper = input.parentElement;
        
        // 移除现有错误
        this.clearInputError(input);
        
        // 添加错误样式
        wrapper.classList.add('error');
        
        // 添加错误消息
        const errorElement = document.createElement('div');
        errorElement.className = 'form-error';
        errorElement.innerHTML = `<i class="fas fa-exclamation-circle"></i> ${message}`;
        wrapper.parentElement.appendChild(errorElement);
    }

    // 清除输入错误
    clearInputError(input) {
        const wrapper = input.parentElement;
        const formGroup = wrapper.parentElement;
        
        wrapper.classList.remove('error', 'success');
        
        const existingError = formGroup.querySelector('.form-error');
        if (existingError) {
            existingError.remove();
        }
    }

    // 显示表单错误
    displayFormErrors(errors) {
        Object.keys(errors).forEach(field => {
            let inputId = field;
            
            // 映射字段名到输入框ID
            switch (field) {
                case 'username':
                    inputId = 'username';
                    break;
                case 'email':
                    inputId = 'email';
                    break;
                case 'current_password':
                    inputId = 'currentPassword';
                    break;
                case 'new_password':
                    inputId = 'newPassword';
                    break;
            }
            
            this.showInputError(inputId, errors[field]);
        });
    }

    // 验证邮箱格式
    isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }

    // 格式化日期
    formatDate(dateString) {
        if (!dateString) return '';
        
        const date = new Date(dateString);
        const now = new Date();
        const diffTime = now - date;
        const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
        
        if (diffDays === 0) {
            return '今天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
        } else if (diffDays === 1) {
            return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
        } else if (diffDays < 7) {
            return `${diffDays}天前`;
        } else {
            return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
        }
    }

    // API请求
    async apiRequest(endpoint, method = 'GET', data = null) {
        const token = localStorage.getItem('auth_token');
        const url = `${this.apiBase}/${endpoint}`;
        
        const options = {
            method,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': token ? `Bearer ${token}` : ''
            },
        };

        if (data && (method === 'POST' || method === 'PUT')) {
            options.body = JSON.stringify(data);
        }

        const response = await fetch(url, options);
        
        if (response.status === 401) {
            // 未授权，清除认证数据并跳转到登录页面
            this.clearAuthData();
            window.location.href = 'auth.html';
            return;
        }
        
        return await response.json();
    }

    // 清除认证数据
    clearAuthData() {
        localStorage.removeItem('auth_token');
        localStorage.removeItem('auth_expires');
        localStorage.removeItem('remember_me');
        localStorage.removeItem('user_info');
    }

    // 显示加载状态
    showLoading() {
        document.getElementById('loadingOverlay').classList.remove('hidden');
        
        // 禁用表单按钮
        const buttons = document.querySelectorAll('.auth-btn');
        buttons.forEach(btn => btn.disabled = true);
    }

    // 隐藏加载状态
    hideLoading() {
        document.getElementById('loadingOverlay').classList.add('hidden');
        
        // 启用表单按钮
        const buttons = document.querySelectorAll('.auth-btn');
        buttons.forEach(btn => btn.disabled = false);
    }

    // 显示通知
    showNotification(message, type = 'info') {
        const container = document.getElementById('notificationContainer');
        
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        
        let icon = 'fas fa-info-circle';
        switch (type) {
            case 'success':
                icon = 'fas fa-check-circle';
                break;
            case 'error':
                icon = 'fas fa-exclamation-circle';
                break;
            case 'warning':
                icon = 'fas fa-exclamation-triangle';
                break;
        }
        
        notification.innerHTML = `
            <div class="notification-content">
                <i class="${icon} notification-icon"></i>
                <span class="notification-message">${message}</span>
                <button class="notification-close" onclick="this.parentElement.parentElement.remove()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
        
        container.appendChild(notification);
        
        // 自动移除通知
        setTimeout(() => {
            if (notification.parentNode) {
                notification.style.animation = 'slideOutRight 0.4s ease-out';
                setTimeout(() => notification.remove(), 400);
            }
        }, 5000);
    }
}

// 标签页切换函数
function showTab(tabName) {
    // 隐藏所有标签页内容
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.remove('active');
    });
    
    // 移除所有标签按钮的活动状态
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // 显示选中的标签页
    document.getElementById(tabName + 'Tab').classList.add('active');
    
    // 激活对应的标签按钮
    const targetBtn = document.querySelector(`[onclick="showTab('${tabName}')"]`);
    if (targetBtn) {
        targetBtn.classList.add('active');
    } else {
        // 如果是通过代码调用，找到对应的按钮
        const buttons = document.querySelectorAll('.tab-btn');
        buttons.forEach(btn => {
            if (btn.textContent.includes(tabName === 'password' ? '修改密码' : '基本信息')) {
                btn.classList.add('active');
            }
        });
    }
}

// 密码显示/隐藏切换
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const button = input.parentElement.querySelector('.toggle-password i');
    
    if (input.type === 'password') {
        input.type = 'text';
        button.className = 'fas fa-eye-slash';
    } else {
        input.type = 'password';
        button.className = 'fas fa-eye';
    }
}

// 初始化个人资料管理器
document.addEventListener('DOMContentLoaded', () => {
    new ProfileManager();
});
